package com.dzsw.parse.sql;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.OrderByElement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.SelectItem;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JSqlParserSample {

    public static void main(String[] args) throws JSQLParserException {
        System.out.println(StringUtils.join(selectItemList(SqlConst.SQL_1), ","));
        System.out.println(StringUtils.join(selectOrderBy(SqlConst.SQL_2), ","));
    }

    private static List<String> selectItemList(String sql) throws JSQLParserException {
        PlainSelect plainSelect = createPlainSelect(sql);
        List<SelectItem<?>> itemList = plainSelect.getSelectItems();
        if (itemList != null) {
            return itemList.stream().map(item -> item.toString()).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    private static List<String> selectOrderBy(String sql) throws JSQLParserException {
        PlainSelect plainSelect = createPlainSelect(sql);
        List<OrderByElement> orderByElements = plainSelect.getOrderByElements();
        if (orderByElements != null) {
            return orderByElements.stream().map(item -> item.toString()).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    private static PlainSelect createPlainSelect(String sql) throws JSQLParserException {
//        CCJSqlParserManager parserManager = new CCJSqlParserManager();
        Select select = (Select) CCJSqlParserUtil.parse(sql);
        return (PlainSelect) select.getSelectBody();
    }
}
